/**
 * 全站路由配置
 *
 * 建议:
 * 1. 代码中路由统一使用name属性跳转(不使用path属性)
 */
import Vue from 'vue'
import Router from 'vue-router'
import http from '@/utils/httpRequest'
import {
  isURL
} from '@/utils/validate'
import {
  clearLoginInfo
} from '@/utils'

Vue.use(Router)

// 开发环境不使用懒加载, 因为懒加载页面太多的话会造成webpack热更新太慢, 所以只有生产环境使用懒加载
const _import = require('./import-' + process.env.NODE_ENV)

// 全局路由(无需嵌套上左右整体布局)
const globalRoutes = [{
    path: '/404',
    component: _import('common/404'),
    name: '404',
    meta: {
      title: '404未找到'
    }
  },
  {
    path: '/login',
    component: _import('common/login'),
    name: 'login',
    meta: {
      title: '登录'
    }
  },
  {
    path: '/merchant',
    component: _import('common/merchant'),
    name: 'merchant',
    meta: {
      title: '商家入驻'
    }
  },
  {
    path: '/merchantClone',
    component: _import('common/merchantClone'),
    name: 'merchantClone',
    meta: {
      title: '商家入驻'
    }
  }
]

// 主入口路由(需嵌套上左右整体布局)
const mainRoutes = {
  path: '/',
  component: _import('main'),
  name: 'main',
  redirect: {
    name: 'home'
  },
  meta: {
    title: '主入口整体布局'
  },
  children: [
    // 通过meta对象设置路由展示方式
    // 1. isTab: 是否通过tab展示内容, true: 是, false: 否
    // 2. iframeUrl: 是否通过iframe嵌套展示内容, '以http[s]://开头': 是, '': 否
    // 提示: 如需要通过iframe嵌套展示内容, 但不通过tab打开, 请自行创建组件使用iframe处理!
    {
      path: '/home',
      component: _import('common/home'),
      name: 'home',
      meta: {
        title: '首页'
      }
    },
    {
      path: '/userList',
      component: _import('user/userList'),
      name: 'userList',
      meta: {
        title: '用户列表',
        isTab: true
      }
    },
    {
      path: '/allocationList',
      component: _import('allocation/allocationList'),
      name: 'allocationList',
      meta: {
        title: '配置列表',
        isTab: true
      }
    },
    {
      path: '/financeList',
      component: _import('finance/financeList'),
      name: 'financeList',
      meta: {
        title: '财务中心',
        isTab: true
      }
    },
		{
		  path: '/userManual',
		  component: _import('shouce/userManual'),
		  name: 'userManual',
		  meta: {
		    title: '用户手册',
		    isTab: true
		  }
		},
    {
      path: '/message',
      component: _import('message/message'),
      name: 'message',
      meta: {
        title: '消息中心',
        isTab: true
      }
    },
    {
      path: '/userDetail',
      component: _import('user/userDetail'),
      name: 'userDetail',
      meta: {
        title: '用户详情',
        isTab: true
      }
    },
    {
      path: '/userDetailclone',
      component: _import('user/userDetailclone'),
      name: 'userDetailclone',
      meta: {
        title: '用户详情',
        isTab: true
      }
    },
    {
      path: '/wechatList',
      component: _import('wechat/wechatList'),
      name: 'wechatList',
      meta: {
        title: '微信配置',
        isTab: true
      }
    },
    {
      path: '/storeList',
      component: _import('store/storeList'),
      name: 'storeList',
      meta: {
        title: '轮播管理',
        isTab: true
      }
    },
    {
      path: '/invitation',
      component: _import('invitationImg/invitationImg'),
      name: 'invitation',
      meta: {
        title: '邀请海报',
        isTab: true
      }
    },
    {
      path: '/materialsList',
      component: _import('materials/materialsList'),
      name: 'materialsList',
      meta: {
        title: '好物圈',
        isTab: true
      }
    },
    {
      path: '/classifyAdmin',
      component: _import('selfShop/classifyAdmin'),
      name: 'classifyAdmin',
      meta: {
        title: '游戏分类',
        isTab: true
      }
    },
    {
      path: '/competition',
      component: _import('competition/competition'),
      name: 'competition',
      meta: {
        title: '王者荣耀',
        isTab: true
      }
    },
		{
		  path: '/competition2',
		  component: _import('competition/competition2'),
		  name: 'competition2',
		  meta: {
		    title: '和平精英',
		    isTab: true
		  }
		},
		{
		  path: '/competition3',
		  component: _import('competition/competition3'),
		  name: 'competition3',
		  meta: {
		    title: '战队赛',
		    isTab: true
		  }
		},
    {
      path: '/addcompet',
      component: _import('competition/addcompet'),
      name: 'addcompet',
      meta: {
        title: '添加赛事',
        isTab: false
      }
    },
    {
      path: '/admencompet',
      component: _import('competition/admencompet'),
      name: 'admencompet',
      meta: {
        title: '修改赛事',
        isTab: false
      }
    },
    {
      path: '/apply',
      component: _import('competition/apply'),
      name: 'apply',
      meta: {
        title: '报名列表',
        isTab: true
      }
    },
    {
      path: '/competvideo',
      component: _import('competition/competvideo'),
      name: 'competvideo',
      meta: {
        title: '视频管理',
        isTab: true
      }
    },
    {
      path: '/comment',
      component: _import('competition/comment'),
      name: 'comment',
      meta: {
        title: '视频评论',
        isTab: true
      }
    },
    {
      path: '/competitionClass',
      component: _import('competition/competitionClass'),
      name: 'competitionClass',
      meta: {
        title: '赛事分类',
        isTab: true
      }
    },
    {
      path: '/ranking',
      component: _import('competition/ranking'),
      name: 'ranking',
      meta: {
        title: '赛事排行榜',
        isTab: true
      }
    },
    {
      path: '/account',
      component: _import('account/account'),
      name: 'account',
      meta: {
        title: '结算列表',
        isTab: true
      }
    },
    {
      path: '/tournamentBonus',
      component: _import('competition/tournamentBonus'),
      name: 'tournamentBonus',
      meta: {
        title: '赛事奖金',
        isTab: true
      }
    },
    {
      path: '/order',
      component: _import('order/order'),
      name: 'order',
      meta: {
        title: '订单中心',
        isTab: true
      }
    },
    {
      path: '/orderDetails',
      component: _import('order/orderDetails'),
      name: 'orderDetails',
      meta: {
        title: '订单详情',
        isTab: true
      }
    },
    {
      path: '/integralist',
      component: _import('integral/integralist'),
      name: 'integralist',
      meta: {
        title: '金币商品',
        isTab: true
      }
    },
    {
      path: '/intepublich',
      component: _import('integral/intepublich'),
      name: 'intepublich',
      meta: {
        title: '添加金币商品',
        isTab: false
      }
    },
    {
      path: '/inteAmend',
      component: _import('integral/inteAmend'),
      name: 'inteAmend',
      meta: {
        title: '修改金币商品',
        isTab: false
      }
    },
	{
	  path: '/ticketList',
	  component: _import('integral/ticketList'),
	  name: 'ticketList',
	  meta: {
		title: '门票商品',
		isTab: true
	  }
	},
	{
	  path: '/ticketAdd',
	  component: _import('integral/ticketAdd'),
	  name: 'ticketAdd',
	  meta: {
		title: '添加门票商品',
		isTab: false
	  }
	},
	{
	  path: '/ticketAmend',
	  component: _import('integral/ticketAmend'),
	  name: 'ticketAmend',
	  meta: {
		title: '修改门票商品',
		isTab: false
	  }
	},
	{
	  path: '/ticketClass',
	  component: _import('integral/ticketClass'),
	  name: 'ticketClass',
	  meta: {
	    title: '门票分类',
	    isTab: true
	  }
	},
    {
      path: '/specification',
      component: _import('integral/specification'),
      name: 'specification',
      meta: {
        title: '商品规格',
        isTab: true
      }
    },
    {
      path: '/virtual',
      component: _import('virtual/virtual'),
      name: 'virtual',
      meta: {
        title: '虚拟商品',
        isTab: true
      }
    },
    {
      path: '/virtualAmend',
      component: _import('virtual/virtualAmend'),
      name: 'virtualAmend',
      meta: {
        title: '兑换码列表',
        isTab: false
      }
    },
    {
      path: '/coupon',
      component: _import('coupon/coupon'),
      name: 'coupon',
      meta: {
        title: '优惠券制作',
        isTab: true
      }
    },
    {
      path: '/couponissue',
      component: _import('coupon/couponissue'),
      name: 'couponissue',
      meta: {
        title: '已发布优惠券',
        isTab: true
      }
    },
    {
      path: '/couponuser',
      component: _import('coupon/couponuser'),
      name: 'couponuser',
      meta: {
        title: '优惠券领取记录',
        isTab: true
      }
    },
    {
      path: '/standings',
      component: _import('competition/standings'),
      name: 'standings',
      meta: {
        title: '战绩列表',
        isTab: true
      }
    },
    {
      path: '/complaint',
      component: _import('competition/complaint'),
      name: 'complaint',
      meta: {
        title: '投诉列表',
        isTab: true
      }
    },
    {
      path: '/prefecture',
      component: _import('competition/prefecture'),
      name: 'prefecture',
      meta: {
        title: '赛事专区',
        isTab: true
      }
    },
    {
      path: '/app',
      component: _import('app/app'),
      name: 'app',
      meta: {
        title: '升级配置',
        isTab: true
      }
    },
    {
      path: '/updateNote',
      component: _import('app/updateNote'),
      name: 'updateNote',
      meta: {
        title: '更新说明',
        isTab: true
      }
    },
    {
      path: '/memberList',
      component: _import('member/memberList'),
      name: 'memberList',
      meta: {
        title: '团长配置',
        isTab: true
      }
    },
    {
      path: '/rankingList',
      component: _import('member/rankingList'),
      name: 'rankingList',
      meta: {
        title: '排行榜',
        isTab: true
      }
    },
	{
	  path: '/memberDetails',
	  component: _import('members/memberDetails'),
	  name: 'memberDetails',
	  meta: {
	    title: '会员配置',
	    isTab: true
	  }
	},
    {
      path: '/vueMchat',
      component: _import('vueMchat/vueMchat'),
      name: 'vueMchat',
      meta: {
        title: '聊天会话',
        isTab: true
      }
    },
		{
		      path: '/protocol',
		      component: _import('protocol/protocol'),
		      name: 'protocol',
		      meta: {
		        title: '协议配置',
		        isTab: true
		      }
		},
		{
		      path: '/protocoladd',
		      component: _import('protocol/protocoladd'),
		      name: 'protocoladd',
		      meta: {
		        title: '添加协议',
		        isTab: true
		      }
		},
		{
		      path: '/protocolAmend',
		      component: _import('protocol/protocolAmend'),
		      name: 'protocolAmend',
		      meta: {
		        title: '修改协议',
		        isTab: true
		      }
		},
		{
		      path: '/playWithAudit',
		      component: _import('playWith/audit'),
		      name: 'playWithAudit',
		      meta: {
		        title: '审核列表',
		        isTab: true
		      }
		},
    {
      path: '/playWithAuditDetail',
      component: _import('playWith/auditDetail'),
      name: 'playWithAuditDetail',
      meta: {
        title: '审核详情',
        isTab: true
      }
    },
		{
		      path: '/playWithList',
		      component: _import('playWith/playerList'),
		      name: 'playWithList',
		      meta: {
		        title: '陪玩列表',
		        isTab: true
		      }
		},
    {
      path: '/playWithDetail',
      component: _import('playWith/playerDetail'),
      name: 'playWithDetail',
      meta: {
        title: '陪玩详情',
        isTab: true
      }
    },
		{
		      path: '/playWithOrder',
		      component: _import('playWith/order'),
		      name: 'playWithOrder',
		      meta: {
		        title: '订单列表',
		        isTab: true
		      }
		},
    {
      path: '/playWithOrderDetail',
      component: _import('playWith/orderDetails'),
      name: 'playWithOrderDetail',
      meta: {
        title: '订单详情',
        isTab: true
      }
    },
		{
		      path: '/playWithEvaluation',
		      component: _import('playWith/evaluation'),
		      name: 'playWithEvaluation',
		      meta: {
		        title: '评论列表',
		        isTab: true
		      }
		},
		{
		      path: '/teamList',
		      component: _import('team/list'),
		      name: 'teamList',
		      meta: {
		        title: '战队列表',
		        isTab: true
		      }
		},
		{
		      path: '/teamDetail',
		      component: _import('team/detail'),
		      name: 'teamDetail',
		      meta: {
		        title: '战队详情',
		        isTab: true
		      }
		},
		{
		      path: '/squareList',
		      component: _import('square/list'),
		      name: 'squareList',
		      meta: {
		        title: '广场列表',
		        isTab: true
		      }
		},
		{
		      path: '/squareDetail',
		      component: _import('square/detail'),
		      name: 'squareDetail',
		      meta: {
		        title: '广场详情',
		        isTab: true
		      }
		},
		{
		      path: '/userSquare',
		      component: _import('userSquare/index'),
		      name: 'userSquare',
		      meta: {
		        title: '用户广场',
		        isTab: true
		      }
		},
		{
		      path: '/userSquareDetails',
		      component: _import('userSquare/details'),
		      name: 'userSquareDetails',
		      meta: {
		        title: '用户广场详情',
		        isTab: true
		      }
		},
    {
          path: '/blindbox',
          component: _import('blindbox/index'),
          name: 'blindbox',
          meta: {
            title: '盲盒列表',
            isTab: true
          }
    },
    {
          path: '/blindboxOrderList',
          component: _import('blindbox/order'),
          name: 'blindboxOrderList',
          meta: {
            title: '订单列表',
            isTab: true
          }
    },
		{
		      path: '/whereasList',
		      component: _import('whereas/list'),
		      name: 'whereasList',
		      meta: {
		        title: '代练列表',
		        isTab: true
		      }
		},
		{
		      path: '/whereasDetail',
		      component: _import('whereas/detail'),
		      name: 'whereasDetail',
		      meta: {
		        title: '代练详情',
		        isTab: true
		      }
		},
    {
      path: '/whereasReview',
      component: _import('whereas/review'),
      name: 'whereasReview',
      meta: {
        title: '审核列表',
        isTab: true
      }
    },
    {
      path: '/whereasOrder',
      component: _import('whereas/order'),
      name: 'whereasOrder',
      meta: {
        title: '订单列表',
        isTab: true
      }
    },
    {
      path: '/whereasOrderDetail',
      component: _import('whereas/orderDetail'),
      name: 'whereasOrderDetail',
      meta: {
        title: '订单详情',
        isTab: true
      }
    },
    {
      path: '/whereasCommission',
      component: _import('whereas/commission'),
      name: 'whereasCommission',
      meta: {
        title: '返佣明细',
        isTab: true
      }
    },
  ],
  beforeEnter(to, from, next) {
    let token = Vue.cookie.get('token')
    if (!token || !/\S/.test(token)) {
      clearLoginInfo()
      next({
        name: 'login'
      })
    }
    next()
  }
}

const router = new Router({
  mode: 'history', //  hash
  scrollBehavior: () => ({
    y: 0
  }),
  isAddDynamicMenuRoutes: false, // 是否已经添加动态(菜单)路由
  routes: globalRoutes.concat(mainRoutes)
})

router.beforeEach((to, from, next) => {
  let userId = Vue.cookie.get('userId')
  // 添加动态(菜单)路由
  // 1. 已经添加 or 全局路由, 直接访问
  // 2. 获取菜单列表, 添加并保存本地存储
    if (userId=='' || router.options.isAddDynamicMenuRoutes || fnCurrentRouteType(to, globalRoutes) === 'global') {
      next()
    } else {
      http({
        url: http.adornUrl2(`/sys/menu/nav?userId=${userId}`),
        method: 'get',
        params: http.adornParams()
      }).then(({
        data
      }) => {
        if (data && data.status === 0) {
          fnAddDynamicMenuRoutes(data.data.menuList)
          router.options.isAddDynamicMenuRoutes = true
          sessionStorage.setItem('menuList', JSON.stringify(data.data.menuList || '[]'))
          sessionStorage.setItem('permissions', JSON.stringify(data.data.permissions || '[]'))
          next({ ...to,
            replace: true
          })
        } else {
          sessionStorage.setItem('menuList', '[]')
          sessionStorage.setItem('permissions', '[]')
          next()
        }
      }).catch((e) => {
        console.log(`%c${e} 请求菜单列表和权限失败，跳转至登录页！！`, 'color:blue')
        router.push({
          name: 'login'
        })
      })
    }

})

/**
 * 判断当前路由类型, global: 全局路由, main: 主入口路由
 * @param {*} route 当前路由
 */
function fnCurrentRouteType(route, globalRoutes = []) {
  var temp = []
  for (var i = 0; i < globalRoutes.length; i++) {
    if (route.path === globalRoutes[i].path) {
      return 'global'
    } else if (globalRoutes[i].children && globalRoutes[i].children.length >= 1) {
      temp = temp.concat(globalRoutes[i].children)
    }
  }
  return temp.length >= 1 ? fnCurrentRouteType(route, temp) : 'main'
}

/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
function fnAddDynamicMenuRoutes(menuList = [], routes = []) {
  var temp = []
  for (var i = 0; i < menuList.length; i++) {
    if (menuList[i].list && menuList[i].list.length >= 1) {
      temp = temp.concat(menuList[i].list)
    } else if (menuList[i].url && /\S/.test(menuList[i].url)) {
      menuList[i].url = menuList[i].url.replace(/^\//, '')
      var route = {
        path: menuList[i].url.replace('/', '-'),
        component: null,
        name: menuList[i].url.replace('/', '-'),
        meta: {
          menuId: menuList[i].menuId,
          title: menuList[i].name,
          isDynamic: true,
          isTab: true,
          iframeUrl: ''
        }
      }
      // url以http[s]://开头, 通过iframe展示
      if (isURL(menuList[i].url)) {
        route['path'] = `i-${menuList[i].menuId}`
        route['name'] = `i-${menuList[i].menuId}`
        route['meta']['iframeUrl'] = menuList[i].url
      } else {
        try {
          route['component'] = _import(`modules/${menuList[i].url}`) || null
        } catch (e) {}
      }
      routes.push(route)
    }
  }
  if (temp.length >= 1) {
    fnAddDynamicMenuRoutes(temp, routes)
  } else {
    mainRoutes.name = 'main-dynamic'
    mainRoutes.children = routes
    router.addRoutes([
      mainRoutes,
      {
        path: '*',
        redirect: {
          name: '404'
        }
      }
    ])
    sessionStorage.setItem('dynamicMenuRoutes', JSON.stringify(mainRoutes.children || '[]'))
    console.log('\n')
    console.log('%c!<-------------------- 动态(菜单)路由 s -------------------->', 'color:blue')
    console.log(mainRoutes.children)
    console.log('%c!<-------------------- 动态(菜单)路由 e -------------------->', 'color:blue')
  }
}

export default router
